package com.meitu.community.servlet;

import com.meitu.community.model.User;
import com.meitu.community.service.UserService;
import com.meitu.community.service.UserServiceImpl;
import com.meitu.community.util.ServletUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@WebServlet("/user/*")
public class UserServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        if (requestURI == null || "".equals(requestURI.trim()) || requestURI.indexOf("/") == requestURI.lastIndexOf("/")) {
            resp.sendRedirect("404.jsp");
            return;
        }
        String methodName = requestURI.substring(requestURI.lastIndexOf("/") + 1);
        ServletUtils.callServletMethod(methodName, this.getClass(), req, resp);
    }

    public void toLogin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("WEB-INF/login.jsp").forward(req, resp);
    }

    public void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User checkUser = new User(username, password);
        try {
            User user = userService.findByUser(checkUser);
            req.getSession().setAttribute("user", user);
            req.getRequestDispatcher("").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            req.getRequestDispatcher("").forward(req, resp);
        }
    }

    public static void main(String[] args) {
        String url = "/user/login";
        System.out.println(url.indexOf("/", 1));
    }

}
